package com.fitz.config;

import com.fitz.enums.SerializerEnum;
import com.fitz.proxy.ProxyFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

/**
 * @author fitz 2021-5-2 15:34
 */

@Configuration
public class RpcBootStrapConfiguration {

    @Value("${server.port:8080}")
    private int port;

    @Value("${fitz.rpc.registry-address}")
    private String registryAddress;

    @Value("${fitz.rpc.server-port:0}")
    private int serverPort = 0;

    @Value("${fitz.rpc.max-pool-size:10}")
    private int maxPoolSize;

    @Value("${fitz.rpc.min-pool-size:1}")
    private int minPoolSize;

    @Value("${fitz.rpc.serializer-type:HESSION}")
    private String serializerType;

    @Bean(name = "providerInitializer")
    public ProviderInitializer initProvider(){
        SerializerEnum serializer = null;
        serializer = SerializerEnum.find(serializerType);
        if (serializer == null){
            serializer = SerializerEnum.HESSIAN2;
        }
        serverPort = serverPort == 0 ? port + 1000: serverPort;

        String[] array = registryAddress.split("://");
        this.registryAddress = array[1];
        String registryType = array[0];

        return new ProviderInitializer(serverPort,registryAddress,serializer.getCode());
    }

    @Bean
    @DependsOn("providerInitializer")
    public ProxyFactory initConsumer(){
        SerializerEnum serializer = null;
            serializer = SerializerEnum.find(serializerType);
            if (serializer == null){
                serializer = SerializerEnum.HESSIAN2;
            }
        return new ProxyFactory(minPoolSize,maxPoolSize, serializer.getCode());
    }

}
